# Utility functions shared among modules belong here.

def get_instance(editor, path):
	for instance in editor.instances:
		if path == ("file://%s" % instance.filename):
			return instance
	return None

def focus_window_and_set_cursor(editor, tag, instance):
	## the regexp in the tag file contains unescaped
	## parentheses. This makes using the 're' module
	## completely useless. re.escape() provides no
	## solution either, so strip the ^ and $ from the
	## regexp and just compare strings
	pattern = tag['pattern'].strip('^').strip('$')
	linenr = 0
	startiter = instance.textbuffer.get_start_iter()
	enditer = instance.textbuffer.get_end_iter()
	text = instance.textbuffer.get_text(startiter, enditer)
	lines = text.split('\n')
	for line in lines:
		if line == pattern:
			break
		else:
			linenr += 1
	
	iterator = instance.textbuffer.get_iter_at_line(linenr)
	instance.textbuffer.place_cursor(iterator)
	instance.move_view_to_cursor(True, iterator)
	editor.focus_by_id(instance.id_)
	return

